```html
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Spring Bean 生命周期详解</title>
    <link href="https://cdn.staticfile.org/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <link href="https://cdn.staticfile.org/tailwindcss/2.2.19/tailwind.min.css" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Noto+Serif+SC:wght@400;500;600;700&family=Noto+Sans+SC:wght@300;400;500;700&display=swap" rel="stylesheet">
    <style>
        body {
            font-family: 'Noto Sans SC', Tahoma, Arial, Roboto, "Droid Sans", "Helvetica Neue", "Droid Sans Fallback", "Heiti SC", "Hiragino Sans GB", Simsun, sans-serif;
            background-color: #f8fafc;
            color: #1a202c;
            line-height: 1.6;
        }
        .hero {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }
        .code-block {
            background-color: #2d3748;
            color: #e2e8f0;
            border-radius: 0.5rem;
            padding: 1rem;
            font-family: 'SFMono-Regular', Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;
        }
        .process-card {
            transition: all 0.3s ease;
            border-left: 4px solid #667eea;
        }
        .process-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1);
        }
        .lifecycle-diagram {
            background-color: white;
            border-radius: 0.5rem;
            padding: 1.5rem;
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
        }
        .first-letter {
            font-size: 3.5rem;
            line-height: 1;
            float: left;
            margin-right: 0.5rem;
            margin-bottom: -0.5rem;
            color: #667eea;
            font-weight: 700;
        }
    </style>
</head>
<body>
    <div class="hero py-20 px-4 sm:px-6 lg:px-8">
        <div class="max-w-5xl mx-auto text-center">
            <h1 class="text-4xl md:text-5xl font-bold mb-6 font-serif">Spring Bean 生命周期详解</h1>
            <p class="text-xl opacity-90 max-w-3xl mx-auto">
                深入理解Spring框架中Bean的创建、初始化、使用和销毁的全过程
            </p>
            <div class="mt-10">
                <span class="inline-block bg-white text-indigo-700 px-6 py-3 rounded-full font-medium shadow-md hover:shadow-lg transition duration-300">
                    <i class="fas fa-code mr-2"></i>Java Spring
                </span>
            </div>
        </div>
    </div>

    <div class="max-w-5xl mx-auto px-4 sm:px-6 lg:px-8 py-12">
        <article class="prose prose-lg max-w-none">
            <section class="mb-16">
                <h2 class="text-3xl font-bold mb-6 text-indigo-800 border-b pb-2">什么是 Bean</h2>
                <div class="bg-white p-6 rounded-lg shadow-md">
                    <p class="text-gray-700 leading-relaxed">
                        <span class="first-letter">在</span>Spring中，由Spring IoC容器管理的构成应用程序主干的对象称为bean。bean是由Spring IoC容器实例化、组装和管理的对象。否则，bean只是应用程序中的众多对象之一。bean及其之间的依赖关系反映在容器使用的配置元数据中，通俗来讲Bean就是我们写的Java类。
                    </p>
                </div>
            </section>

            <section class="mb-16">
                <h2 class="text-3xl font-bold mb-6 text-indigo-800 border-b pb-2">普通对象(Bean)的生命周期</h2>
                <div class="bg-white p-6 rounded-lg shadow-md">
                    <ul class="list-disc pl-6 space-y-2 text-gray-700">
                        <li>实例化</li>
                        <li>该对象不再被使用时通过垃圾回收机制进行回收</li>
                    </ul>
                    
                    <div class="mt-6">
                        <div class="code-block">
                            <pre><code>public static void main(String[] args) {
    // 1.实例化
    User user = new User();
 
    // 2、使用对象
    user.setName("toString");
    user.getName();
    
    // 3.user对象不再使用就会被JVM回收
    user = null;
}</code></pre>
                        </div>
                    </div>
                    
                    <div class="mt-6 flex justify-center">
                        <img src="https://cdn.nlark.com/yuque/0/2022/png/21449790/1644221695045-3f977dbd-f885-4948-bf10-019d24d065c2.png" alt="普通对象生命周期" class="rounded-lg shadow-md">
                    </div>
                </div>
            </section>

            <section class="mb-16">
                <h2 class="text-3xl font-bold mb-6 text-indigo-800 border-b pb-2">Spring Bean初始化的流程</h2>
                <div class="bg-white p-6 rounded-lg shadow-md">
                    <div class="flex justify-center mb-6">
                        <img src="https://cdn.nlark.com/yuque/0/2023/png/21449790/1681292515303-3c089ed3-0d55-4c8d-9c54-7c354781567f.png" alt="Spring Bean初始化流程" class="rounded-lg shadow-md">
                    </div>
                    
                    <div class="grid md:grid-cols-2 gap-6 mt-8">
                        <div class="process-card bg-white p-6 rounded-lg shadow-sm">
                            <h3 class="text-xl font-semibold mb-3 text-indigo-700">1. 实例化 Instantiation</h3>
                            <p class="text-gray-700">调用构造器创建对象</p>
                        </div>
                        <div class="process-card bg-white p-6 rounded-lg shadow-sm">
                            <h3 class="text-xl font-semibold mb-3 text-indigo-700">2. 属性赋值 Populate</h3>
                            <p class="text-gray-700">依赖注入(controller中要注入service)</p>
                        </div>
                        <div class="process-card bg-white p-6 rounded-lg shadow-sm">
                            <h3 class="text-xl font-semibold mb-3 text-indigo-700">3. 初始化 Initialization</h3>
                            <p class="text-gray-700">Spring初始化的方法，init</p>
                        </div>
                        <div class="process-card bg-white p-6 rounded-lg shadow-sm">
                            <h3 class="text-xl font-semibold mb-3 text-indigo-700">4. 销毁 Destruction</h3>
                            <p class="text-gray-700">容器关闭</p>
                        </div>
                    </div>
                    
                    <div class="mt-8">
                        <img src="https://cdn.nlark.com/yuque/0/2021/png/21449790/1631461743714-8b5acb92-e417-47a2-8090-2d33336c4886.png" alt="Spring Bean生命周期详细流程" class="rounded-lg shadow-md w-full">
                    </div>
                    
                    <div class="mt-8">
                        <div class="code-block">
                            <pre><code>// AbstractAutowireCapableBeanFactory.java
protected Object doCreateBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
        throws BeanCreationException {

    // Instantiate the bean.
    BeanWrapper instanceWrapper = null;
    if (mbd.isSingleton()) {
        instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
    }
    if (instanceWrapper == null) {
        // 1.实例化
        instanceWrapper = createBeanInstance(beanName, mbd, args);
    }
    // Initialize the bean instance.
    try {
        // 2.赋值(DI)
        populateBean(beanName, mbd, instanceWrapper);
        
        // 3.初始化
        exposedObject = initializeBean(beanName, exposedObject, mbd);
    }
    catch (Throwable ex) {
        if (ex instanceof BeanCreationException && beanName.equals(((BeanCreationException) ex).getBeanName())) {
            throw (BeanCreationException) ex;
        }
        else {
            throw new BeanCreationException(
                    mbd.getResourceDescription(), beanName, "Initialization of bean failed", ex);
        }
    }
    return exposedObject;
}</code></pre>
                        </div>
                    </div>
                    
                    <div class="mt-6">
                        <p class="text-gray-700">容器关闭时调用<span class="bg-red-100 text-red-800 px-2 py-1 rounded">ConfigurableApplicationContext#close()</span>销毁对象</p>
                        <div class="code-block mt-4">
                            <pre><code>public void close() {
    synchronized (this.startupShutdownMonitor) {
        doClose();
        if (this.shutdownHook != null) {
            try {
                Runtime.getRuntime().removeShutdownHook(this.shutdownHook);
            }
            catch (IllegalStateException ex) {
                // ignore - VM is already shutting down
            }
        }
    }
}</code></pre>
                        </div>
                    </div>
                </div>
            </section>

            <section class="mb-16">
                <h2 class="text-3xl font-bold mb-6 text-indigo-800 border-b pb-2">SpringBean生命周期函数分类</h2>
                <div class="bg-white p-6 rounded-lg shadow-md">
                    <div class="grid md:grid-cols-2 gap-6">
                        <div class="process-card bg-white p-6 rounded-lg shadow-sm">
                            <h3 class="text-xl font-semibold mb-3 text-indigo-700"><i class="fas fa-cube mr-2"></i>Bean自身的方法</h3>
                            <p class="text-gray-700">这个包括了Bean本身调用的方法和通过配置文件中&lt;bean&gt;的<span class="font-bold">init-method</span>和<span class="font-bold">destroy-method</span>指定的方法</p>
                        </div>
                        <div class="process-card bg-white p-6 rounded-lg shadow-sm">
                            <h3 class="text-xl font-semibold mb-3 text-indigo-700"><i class="fas fa-layer-group mr-2"></i>Bean级生命周期的方法</h3>
                            <p class="text-gray-700">这个包括了<span class="font-bold">BeanNameAware、BeanFactoryAware、InitializingBean和DiposableBean</span>这些接口的方法</p>
                        </div>
                        <div class="process-card bg-white p-6 rounded-lg shadow-sm">
                            <h3 class="text-xl font-semibold mb-3 text-indigo-700"><i class="fas fa-cogs mr-2"></i>容器生命周期方法</h3>
                            <p class="text-gray-700">这个包括了<span class="font-bold">InstantiationAwareBeanPostProcessor 和 BeanPostProcessor</span>这两个接口实现，一般称它们的实现类为"后处理器"。</p>
                        </div>
                        <div class="process-card bg-white p-6 rounded-lg shadow-sm">
                            <h3 class="text-xl font-semibold mb-3 text-indigo-700"><i class="fas fa-industry mr-2"></i>工厂后处理器接口方法</h3>
                            <p class="text-gray-700">这个包括了<span class="font-bold">AspectJWeavingEnabler, ConfigurationClassPostProcessor, CustomAutowireConfigurer</span>等等非常有用的工厂后处理器接口的方法。工厂后处理器也是容器级的。在应用上下文装配配置文件之后立即调用。</p>
                        </div>
                    </div>
                </div>
            </section>

            <section class="mb-16">
                <h2 class="text-3xl font-bold mb-6 text-indigo-800 border-b pb-2">代码演示生命周期</h2>
                <div class="bg-white p-6 rounded-lg shadow-md">
                    <h3 class="text-2xl font-semibold mb-4 text-indigo-700">1、Bean自身的方法和Bean级生命周期接口方法</h3>
                    <div class="code-block">
                        <pre><code>package com.qf.scope;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;

/**
 */
public class Person implements BeanFactoryAware, BeanNameAware,
        InitializingBean, DisposableBean {

    private String name;
    private String address;
    private int phone;

    private BeanFactory beanFactory;
    private String beanName;

    public Person() {
        System.out.println("【构造器】调用Person的构造器实例化");
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        System.out.println("【注入属性】注入属性name");
        this.name = name;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        System.out.println("【注入属性】注入属性address");
        this.address = address;
    }

    public int getPhone() {
        return phone;
    }

    public void setPhone(int phone) {
        System.out.println("【注入属性】注入属性phone");
        this.phone = phone;
    }

    @Override
    public String toString() {
        return "Person [address=" + address + ", name=" + name + ", phone="
                + phone + "]";
    }

    // 这是BeanFactoryAware接口方法
    @Override
    public void setBeanFactory(BeanFactory arg0) throws BeansException {
        System.out
                .println("【BeanFactoryAware接口】调用BeanFactoryAware.setBeanFactory()");
        this.beanFactory = arg0;
    }

    // 这是BeanNameAware接口方法
    @Override
    public void setBeanName(String arg0) {
        System.out.println("【BeanNameAware接口】调用BeanNameAware.setBeanName()");
        this.beanName = arg0;
    }

    // 这是InitializingBean接口方法
    @Override
    public void afterPropertiesSet() throws Exception {
        System.out
                .println("【InitializingBean接口】调用InitializingBean.afterPropertiesSet()");
    }

    // 这是DiposibleBean接口方法
    @Override
    public void destroy() throws Exception {
        System.out.println("【DiposibleBean接口】调用DiposibleBean.destory()");
    }

    // 通过&lt;bean&gt;的init-method属性指定的初始化方法
    public void myInit() {
        System.out.println("【init-method】调用&lt;bean&gt;的init-method属性指定的初始化方法");
    }

    // 通过&lt;bean&gt;的destroy-method属性指定的初始化方法
    public void myDestory() {
        System.out.println("【destroy-method】调用&lt;bean&gt;的destroy-method属性指定的初始化方法");
    }
}</code></pre>
                    </div>

                    <h3 class="text-2xl font-semibold mt-8 mb-4 text-indigo-700">2、BeanPostProcessor接口的方法</h3>
                    <div class="code-block">
                        <pre><code>package com.qf.scope;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;

public class MyBeanPostProcessor implements BeanPostProcessor {

    public MyBeanPostProcessor() {
        super();
        System.out.println("这是BeanPostProcessor实现类构造器！！");
        // TODO Auto-generated constructor stub
    }

    @Override
    public Object postProcessAfterInitialization(Object arg0, String arg1)
            throws BeansException {
        System.out
        .println("BeanPostProcessor接口方法postProcessAfterInitialization对属性进行更改！");
        return arg0;
    }

    @Override
    public Object postProcessBeforeInitialization(Object arg0, String arg1)
            throws BeansException {
        System.out
        .println("BeanPostProcessor接口方法postProcessBeforeInitialization对属性进行更改！");
        return arg0;
    }
}</code></pre>
                    </div>

                    <h3 class="text-2xl font-semibold mt-8 mb-4 text-indigo-700">3、InstantiationAwareBeanPostProcessorAdapter 接口方法</h3>
                    <div class="code-block">
                        <pre><code>package com.qf.scope;

import java.beans.PropertyDescriptor;

import org.springframework.beans.BeansException;
import org.springframework.beans.PropertyValues;
import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessorAdapter;

public class MyInstantiationAwareBeanPostProcessor extends
        InstantiationAwareBeanPostProcessorAdapter {

    public MyInstantiationAwareBeanPostProcessor() {
        super();
        System.out
                .println("这是InstantiationAwareBeanPostProcessorAdapter实现类构造器！！");
    }

    // 接口方法、实例化Bean之前调用
    @Override
    public Object postProcessBeforeInstantiation(Class beanClass,
            String beanName) throws BeansException {
        System.out
                .println("InstantiationAwareBeanPostProcessor调用postProcessBeforeInstantiation方法");
        return null;
    }

    // 接口方法、实例化Bean之后调用
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName)
            throws BeansException {
        System.out
                .println("InstantiationAwareBeanPostProcessor调用postProcessAfterInitialization方法");
        return bean;
    }

    // 接口方法、设置某个属性时调用
    @Override
    public PropertyValues postProcessPropertyValues(PropertyValues pvs,
            PropertyDescriptor[] pds, Object bean, String beanName)
            throws BeansException {
        System.out
                .println("InstantiationAwareBeanPostProcessor调用postProcessPropertyValues方法");
        return pvs;
    }
}</code></pre>
                    </div>

                    <h3 class="text-2xl font-semibold mt-8 mb-4 text-indigo-700">4、后置处理器接口方法</h3>
                    <div class="code-block">
                        <pre><code>package springBeanTest;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;

public class MyBeanFactoryPostProcessor implements BeanFactoryPostProcessor {

    public MyBeanFactoryPostProcessor() {
        super();
        System.out.println("这是BeanFactoryPostProcessor实现类构造器！！");
    }

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory arg0)
            throws BeansException {
        System.out
                .println("BeanFactoryPostProcessor调用postProcessBeanFactory方法");
        BeanDefinition bd = arg0.getBeanDefinition("person");
        bd.getPropertyValues().addPropertyValue("phone", "110");
    }

}</code></pre>
                    </div>

                    <h3 class="text-2xl font-semibold mt-8 mb-4 text-indigo-700">5、配置文件如下beans.xml</h3>
                    <div class="code-block">
                        <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt;

&lt;beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
       xmlns:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="
            http://www.springframework.org/schema/beans 
            http://www.springframework.org/schema/beans/spring-beans-3.2.xsd"&gt;

    &lt;bean id="beanPostProcessor" class="springBeanTest.MyBeanPostProcessor"&gt;
    &lt;/bean&gt;

    &lt;bean id="instantiationAwareBeanPostProcessor" class="springBeanTest.MyInstantiationAwareBeanPostProcessor"&gt;
    &lt;/bean&gt;

    &lt;bean id="beanFactoryPostProcessor" class="springBeanTest.MyBeanFactoryPostProcessor"&gt;
    &lt;/bean&gt;
    
    &lt;bean id="person" class="springBeanTest.Person" init-method="myInit"
        destroy-method="myDestory" scope="singleton" p:name="张三" p:address="深圳"
        p:phone="10086" /&gt;

&lt;/beans&gt;</code></pre>
                    </div>

                    <h3 class="text-2xl font-semibold mt-8 mb-4 text-indigo-700">6、测试</h3>
                    <div class="code-block">
                        <pre><code>@Test
public void test1(){
    ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
    Person person = ctx.getBean("person", Person.class);
    System.out.println(person);
    ctx.close();
}</code></pre>
                    </div>
                </div>
            </section>

            <section class="mb-16">
                <h2 class="text-3xl font-bold mb-6 text-indigo-800 border-b pb-2">SpringBean生命周期源码演示</h2>
                <div class="bg-white p-6 rounded-lg shadow-md">
                    <div class="code-block">
                        <pre><code>public void refresh() throws BeansException, IllegalStateException {
    synchronized (this.startupShutdownMonitor) {
        // 准备，记录容器的启动时间startupDate, 标记容器为激活，初始化上下文环境如文件路径信息，验证必填属性是否填写
        prepareRefresh();

        // 获取新的beanFactory，销毁原有beanFactory、为每个bean生成BeanDefinition等
        ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

        // 初始化beanFactory的各种属性
        prepareBeanFactory(beanFactory);

        try {
            // 模板方法，此时，所有的beanDefinition已经加载，但是还没有实例化。
            //允许在子类中对beanFactory进行扩展处理。比如添加ware相关接口自动装配设置，添加后置处理器等，是子类扩展prepareBeanFactory(beanFactory)的方法
            postProcessBeanFactory(beanFactory);

            // 实例化并调用所有注册的beanFactory后置处理器（实现接口BeanFactoryPostProcessor的bean，在beanFactory标准初始化之后执行）
            invokeBeanFactoryPostProcessors(beanFactory);

            //注册bean后置处理器
            registerBeanPostProcessors(beanFactory);

            // 初始化上下文的消息
            initMessageSource();

            // 初始化事件
            initApplicationEventMulticaster();

            // 模板方法，在容器刷新的时候可以自定义逻辑，不同的Spring容器做不同的事情。
            onRefresh();

            // 注册监听器，广播early application events
            registerListeners();

            // 实例化所有剩余的（非懒加载）单例
            // 比如invokeBeanFactoryPostProcessors方法中根据各种注解解析出来的类，在这个时候都会被初始化。
            // 实例化的过程各种BeanPostProcessor开始起作用。
            finishBeanFactoryInitialization(beanFactory);

            // refresh做完之后需要做的其他事情。
            // 清除上下文资源缓存（如扫描中的ASM元数据）
            // 初始化上下文的生命周期处理器，并刷新（找出Spring容器中实现了Lifecycle接口的bean并执行start()方法）。
            // 发布ContextRefreshedEvent事件告知对应的ApplicationListener进行响应的操作
            finishRefresh();
        }

        catch (BeansException ex) {
            if (logger.isWarnEnabled()) {
                logger.warn("Exception encountered during context initialization - " +
                        "cancelling refresh attempt: " + ex);
            }

            // 销毁已经生成的bean
            destroyBeans();

            // 重置激活状态.
            cancelRefresh(ex);

            // Propagate exception to caller.
            throw ex;
        }

        finally {
            // Reset common introspection caches in Spring's core, since we
            // might not ever need metadata for singleton beans anymore...
            resetCommonCaches();
        }
    }
}</code></pre>
                    </div>
                </div>
            </section>
        </article>
    </div>
</body>
</html>
```